/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
$(function () {
    org.breezee.page = {
        init: function () {
            Dolphin.form.parse();
            this._orgTree = this.orgTree('#orgTree');
            this._deviceList = this.deviceList("#deviceList");
            this._accountList = this.accountList("#accountList");
            this._selectList = this.selectUserList('#selectedList');
            this._unSelectList = this.unSelectUserList('#unselectedList');
            this.initEvent();
            $('.dropdown-toggle').dropdown();
        },
        /**
         * 初始化事件
         */
        initEvent: function () {
            let me = this;
            $(".newOrg").click(function () {
                Dolphin.form.empty('.edit-form');
                $('#data_win').modal('show');
            });

            $(".newDir").click(function () {
                Dolphin.form.empty('.dir-form');
                let checkedData = me._orgTree.getChecked();
                if (checkedData.length == 0) {
                    Dolphin.alert('请选择一个客户');
                    return;
                }
                Dolphin.form.setValue({
                    parent: {
                        id: checkedData[0].id
                    },
                    category: '2'
                }, '.dir-form');
                $('#dirDataModal').modal('show');
            });

            $(".newShop").click(function () {
                Dolphin.form.empty('.shop-form');
                let checkedData = me._orgTree.getChecked();
                if (checkedData.length == 0) {
                    Dolphin.alert('请选择一个客户或者目录');
                    return;
                }
                Dolphin.form.setValue({
                    parent: {
                        id: checkedData[0].id
                    },
                    category : '3',
                    level : '4'
                }, '.shop-form');

                $('#timeZone').val(8);
                $('#shop_win').modal('show');
            });

            $(".customerAccount").click(function () {
                let checked = me._orgTree.getChecked();
                if (checked.length == 0) {
                    Dolphin.alert('请选择一个客户');
                    return;
                }
                $("#org_relation_win").modal('show');
            });

            $('.relation_submit').click(function () {
                let data = {};
                data.id = me.selectData.id;
                data.accounts = [];
                let selData = me._selectList.data.rows;
                for (let i = 0; i < selData.length; i++) {
                    data.accounts.push({id: selData[i].id});
                }
                Dolphin.ajax({
                    url: '/api/958ec455d9334fe39839837dccbdc070',
                    type: Dolphin.requestMethod.POST,
                    data: Dolphin.json2string(data),
                    onSuccess: function (reData) {
                        me._accountList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                            "customer_id_obj_ae": me.selectData.id
                        });
                        $('#org_relation_win').modal('hide');
                    }
                });
            });

            $('[change]').click(function () {
                let thisButton = $(this), allFlag = !!thisButton.attr('all'),
                    sourceList, targetList,
                    checkedData,
                    i;
                if (thisButton.attr("change") == "select") {
                    sourceList = me._unSelectList;
                    targetList = me._selectList;
                } else {
                    sourceList = me._selectList;
                    targetList = me._unSelectList;
                }
                if (allFlag) {
                    checkedData = [].concat(sourceList.data.rows);
                } else {
                    checkedData = sourceList.getChecked();
                }
                for (i = 0; i < checkedData.length; i++) {
                    if (!checkedData[i].inheritFlag) {
                        sourceList.removeRow(checkedData[i].__id__);
                        targetList.addRowWithData(checkedData[i]);
                    }
                }
            });

            $('#org_relation_win').on('show.bs.modal', function (e) {
                me._selectList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                    "customer_obj": me.selectData.id,
                    "pageSize": "-1"
                });
                me._unSelectList.load('/api/756af3ae31a64565a54ec0221f84d377', {"customer_obj_not": me.selectData.id});
            });

            $("#deviceAdd").click(function () {
                Dolphin.form.empty('.device-form');
                let checkedData = me._orgTree.getChecked();
                console.log(checkedData);
                if (checkedData.length == 0 || checkedData[0].category != 3) {
                    Dolphin.alert('请选择一个门店');
                    return;
                }
                Dolphin.form.setValue({
                    customer: {
                        id: checkedData[0].id
                    }
                }, '.device-form');
                $("#device_model").modal('show');
            });
            /**
             * 保存按钮
             */
            $(".btn_submit").click(function () {
                let ef = $("." + $(this).data('cla')), closeWin = $('#' + $(this).data('win'));
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    if (data.parent && !data.parent.id)
                        delete data.parent;
                    data.category = data.category || '1';
                    data.level = data.level || '2';
                    console.log('data.category : '+data.category);
                    console.log('data.level : ' + data.level);
                    Dolphin.ajax({
                        url: '/api/742445c653654caaa4a1fa69eb651a9a',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._orgTree.reload();
                            closeWin.modal('hide');
                        }
                    });

                }
            });

            $(".device_submit").click(function () {
                let ef = $("." + $(this).data('cla')), closeWin = $('#' + $(this).data('win'));
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    Dolphin.ajax({
                        url: '/api/b6a1808e4fcd4844836eb802249ac30c',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._deviceList.load('/api/b6a1808e4fcd4844836eb802249ac30c', {
                                customer_id_obj_ae: me.selectData.id
                            });
                            closeWin.modal('hide');
                        }
                    });

                }
            });
        },
        /**
         * 组织树
         * @returns {*|TREE}
         */
        orgTree: function () {
            let me = this;
            var accountType = org.breezee.context.userData.accountType;
            var url;
            switch(accountType){
                case 3: //渠道商
                    url = '/api/2e1cf2a68bf64264bdc4bf500b751dd9@vendorId='+org.breezee.context.userData.vendorId;
                    break;
                default: //其它
                    url = '/api/2e1cf2a68bf64264bdc4bf500b751dd8@parentId=-1';

            }

            return new Dolphin.TREE({
                panel: arguments[0],
                url: url,
                // mockPathData: ['id'],
                // defaultId: '-1',
                multiple: false,
                nameField: function (data) {
                    return data.name;
                },
                onChecked: function (data) {
                    me.selectData = data;
                    if(data.category=='1') {
                        if (!data.sourceCaption)
                            data.sourceCaption = Dolphin.enum.getEnumText("source", data.source) || data.source;
                        if (!data.industryCaption)
                            data.industryCaption = Dolphin.enum.getEnumText("industry", data.industry);
                        Dolphin.form.setValue(data, '#baseInfo');
                    }
                    // me._accountList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                    //     "customer_id_obj_ae": data.id
                    // });
                    if(data.category != '3'){
                        me._deviceList.load(('/api/742445c653654caaa4a1fa69eb651a9a'),{
                            "parent_id_obj_ae":data.id,
                            "category":"3"
                        });
                    }

                },
                onLoad: function () {
                    // if (me._orgTree.data.length > 0)
                    //     me._orgTree.expend(me._orgTree.data[0]);
                },
                formatterExpend: function (node, renderTree) {
                    //this   thisTree
                    //node   展开点击的所有信息
                    //renderTree   返回数据以后的回调函数，这个必须要调用，
                    //例如：
                    let childrenData;
                    switch(node.level){//1代表渠道商 2代表客户 3代表目录 4代表店铺 5代表设备

                        case '2':
                            Dolphin.ajax({
                                url: '/api/25712cc627f749889af30df1828fdc11@parentId='+node.id,
                                onSuccess: function (data) {
                                    renderTree(data);
                                }
                            });
                            break;
                        case '3':
                            Dolphin.ajax({
                                url: '/api/25712cc627f749889af30df1828fdc11@parentId='+node.id,
                                onSuccess: function (data) {
                                    renderTree(data);
                                }
                            });
                            break;
                        case '4':
                            Dolphin.ajax({
                                url: '/api/8ef98356469e46f3b53ae876000fc613@parentId='+node.id,
                                onSuccess: function (data) {
                                    renderTree(data);
                                }
                            });
                            break;
                        default:
                            childrenData = {rows:[{code:0, name:Dolphin.i18n.get("framework.negtive")}]};
                            renderTree(childrenData);

                    }
                }
            });
        },
        /**
         *  设备列表
         * @param panelId
         * @returns {*|LIST}
         */
        deviceList: function (panelId) {
            let me = this;
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: '门店名称'
                }, {
                    code: 'code',
                    title: '门店编码'
                }, {
                    code: 'province',
                    title: '省份'
                }, {
                    code: 'city',
                    title: '城市'
                },{
                    code: 'openTime',
                    title: '营业时间',
                    formatter:function (val,row) {
                        return row.openTime+"-"+row.closeTime;
                    }
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '180px',
                    formatter: function (val, row, index) {
                        return org.breezee.buttons.edit({
                                id: row.id
                            }) + org.breezee.buttons.del({
                                id: row.id
                            });
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: false,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: true,
                onLoadSuccess: function (data) {
                    org.breezee.buttons.editCallback('1423c7225d134248944babc34f3a36f4', 'id', function (reData) {
                        reData.value.parent = {
                            id: reData.value.parentId
                        };
                        Dolphin.form.setValue(reData.value, '.shop-form');
                        console.log(reData.value);
                        $("#shop_win").modal('show');
                    });
                    org.breezee.buttons.delCallback('1423c7225d134248944babc34f3a36f4', 'id', function (reData) {
                        me._deviceList.load('/api/b6a1808e4fcd4844836eb802249ac30c', {
                            customer_id_obj_ae: me.selectData.id
                        });
                    });
                }
            });
        },

        accountList: function (panelId) {
            let me = this;
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                panelType:'panel-info',
                title: '关联账号',
                columns: [{
                    code: 'name',
                    title: '账号名称'
                }, {
                    code: 'code',
                    title: '账号编码',
                    width: '150px'
                }],
                multiple: true,
                rowIndex: true,
                checkbox: false,
                ajaxType: Dolphin.requestMethod.POST,
                data:{rows:[]},
                pagination: false,
                onLoadSuccess: function () {

                }
            });
        },

        selectUserList: function (panelId) {
            return new Dolphin.LIST({
                panel: panelId,
                panelType: 'panel-warning',
                title: '已选择列表',
                idField: 'id',
                maxHeight: '400px',
                columns: [{
                    code: 'name',
                    title: '用户名称',
                    width: '120px'
                }, {
                    code: 'code',
                    title: '用户编码',
                    width: '100px'
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: false
            });
        },
        unSelectUserList: function (panelId) {
            return new Dolphin.LIST({
                panel: panelId,
                title: '未选择列表',
                panelType: 'panel-info',
                maxHeight: '650px',
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: '用户名称',
                    width: '120px'
                }, {
                    code: 'code',
                    title: '用户编码',
                    width: '100px'
                }],
                multiple: true,
                rowIndex: false,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: true
            });
        }
    };
    org.breezee.page.init();
});